package com.stottlerhenke.simbionic.editor.parser;

import com.stottlerhenke.simbionic.api.SB_VarType;
import com.stottlerhenke.simbionic.common.parser.ETernaryOp;


public class SB_TernaryOpNode extends SB_ParseNode {
  private SB_ParseNode _arg1;
  private SB_ParseNode _arg2;
  private SB_ParseNode _arg3;
  private ETernaryOp _op;

  public SB_TernaryOpNode(SB_ParseNode arg1, SB_ParseNode arg2, SB_ParseNode arg3, ETernaryOp op) {
    _arg1 = arg1;
    _arg2 = arg2;
    _arg3 = arg3;
    _op = op;
    _type = DetermineResultType();
  }
  public SB_ErrorNode GetNextError(SB_ErrorNode lastError) {
    SB_ErrorNode nextError = _arg1.GetNextError(lastError);
    if ((nextError == null) && (_arg2 != null))
    {
        nextError = _arg2.GetNextError(lastError);
        if ((nextError == null) && (_arg3 != null))
        {
            nextError = _arg3.GetNextError(lastError);
        }
    }
    return nextError;
  }
  
  public boolean IsValid()
  {
      return (_arg1.IsValid() && _arg2.IsValid() && _arg3.IsValid());
  }
  
  public boolean ContainsVariable(String varName) 
  {
      return (_arg1.ContainsVariable(varName) || _arg2.ContainsVariable(varName) || _arg3.ContainsVariable(varName));
  }
  
  public boolean ContainsFunction(String funcName) 
  {
      return (_arg1.ContainsFunction(funcName) || _arg2.ContainsFunction(funcName) || _arg3.ContainsFunction(funcName));
  }
  
  public String ToString() 
  {
      return new String(_arg1.ToString() + " ? " + _arg2.ToString() + " : " + _arg3.ToString());
  }
  
  private SB_VarType DetermineResultType()
  {
      // no guarantee that we can absolutely determine the return type
      return (_arg2.GetType() == _arg3.GetType()) ? _arg2.GetType() : SB_VarType.kAny;
  }

  
   /**
    * @return the operator
    */
   ETernaryOp GetOperator() { return _op; }

   /**
    * @return the first argument
    */
   SB_ParseNode GetFirstArg() { return _arg1; }

   /**
    * @return the second argument
    */
   SB_ParseNode GetSecondArg() { return _arg2; }

   /**
    * @return the third argument
    */
   SB_ParseNode GetThirdArg() { return _arg3; }

}